from client.http import readurl, encode

class VDiskAPI:
    def __init__(self, userid, password, client_id='', client_secret='', redirect_uri='', code=None):
        self.userid = userid
        self.password = password
        self.client_id = client_id
        self.client_secret = client_secret
        self.redirect_uri = redirect_uri
        self.code = code
        self.state=''
        
    def authorize(self, response_type = "code" ):
        import urllib2, urlparse, re, cookielib
        class RedirectHandler(urllib2.HTTPRedirectHandler):
            def __init__(self, vdisk):
                self.vdisk = vdisk
            def _get_verifier(self, headers):
                location = headers.get('location', '')
                redirect_url = urlparse.urlparse(location)
                param = urlparse.parse_qs(redirect_url.query)
                if self.vdisk.state == param.get('state', [''])[0]:
                    self.vdisk.code = param.get('code', [''])[0]
                    self.vdisk.access_token = param.get('access_token', [''])[0]
            def http_error_301(self, req, fp, code, msg, headers):
                self._get_verifier(headers)
                return urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, headers)
            def http_error_302(self, req, fp, code, msg, headers):
                self._get_verifier(headers)
                return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
                 
        cj = cookielib.LWPCookieJar()
        cookie_support = urllib2.HTTPCookieProcessor(cj)
        opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler, RedirectHandler(self))
        #request login page
        url = 'https://auth.sina.com.cn/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=%s&display=%s&state=%s' % \
            (self.client_id, encode(self.redirect_uri), response_type, 'mobile', self.state) 
        try:
            login_page, _ = readurl(url, opener=opener)
            print login_page
        except Exception, e:
            print e
            return False
        #auto login
        hiddens = re.findall(r'<input\s+type\s*=\s*["\']hidden["\']\s+name\s*=\s*["\'](?P<name>\w*)["\']\s+value\s*=\s*["\'](?P<value>[\w:/\.]*)["\']\s*/?>', login_page)
        data = {n: v for n, v in hiddens}
        data['userid'] = self.userid
        data['password'] = self.password
        data = '&'.join(encode(data))
        
        referer = url
        url = 'https://auth.sina.com.cn/oauth2/authorize'
        try:
            data, _ = readurl(url, data, referer, opener)
            print data
        except Exception, e:
            print e
        return True


if __name__=='__main__':
    api = VDiskAPI('davidwangtf@gmail.com', 'wtf521107wtf', client_id='3519182922', redirect_uri='http://netdiskfs.egopie.com')
    api.authorize()
    